function InitialClick() {
    document.getElementById("InitialButton").style.display = "none";
    document.getElementById("InitialButton1").style.display = "block";
    document.getElementById("InitialButton2").style.display = "block";
    document.getElementById("InitialButton4").style.display = "block";
}
function ShowInitialClick() {
    document.getElementById("InitialButton").style.display = "block";
    document.getElementById("InitialButton1").style.display = "none";
    document.getElementById("InitialButton2").style.display = "none";
    document.getElementById("InitialButton4").style.display = "none";
}

function close_win() {
    document.querySelectorAll("audio").forEach((audio) => audio.pause());
    currentTimestamp = Date.now();
    operationName = "end";
    additionalInfo = "out";
    CommonNetWork();
    api.openWin({
        name: "ExpressionImitateSelect",
        url: "./ExpressionImitateSelect.html",
        pageParam: {
            uid: userid,
            token: token,
        },
        reload: true,
    });
}

function ResetClick() {
    history.go(0);
}
function ImgAudioClick() {
    document.getElementById("audioBody").play();
}

//表情模仿的录制视频
async function getMediaStream() {
    const hasCameraPermission = hasPermissionObj("camera");
    const hasMicrophonePermission = hasPermissionObj("microphone");
    if (!hasCameraPermission || !hasCameraPermission[0] || !hasCameraPermission[0].granted) {
        api.confirm(
            {
                title: "提醒",
                msg: "没有获得 " + "相机" + " 权限\n是否前往设置？",
                buttons: ["去设置", "取消"],
            },
            function (ret, err) {
                if (1 == ret.buttonIndex) {
                    reqPermission("camera");
                    history.go(0);
                }
            }
        );
        return false;
    } else if (!hasMicrophonePermission || !hasMicrophonePermission[0] || !hasMicrophonePermission[0].granted) {
        api.confirm(
            {
                title: "提醒",
                msg: "没有获得 " + "麦克风" + " 权限\n是否前往设置？",
                buttons: ["去设置", "取消"],
            },
            function (ret, err) {
                if (1 == ret.buttonIndex) {
                    reqPermission("microphone");
                    history.go(0);
                }
            }
        );
        return false;
    } else {
        // 已授予权限，直接获取媒体流
        videoStream = await navigator.mediaDevices.getUserMedia({
            video: { facingMode: "user", width: 1920, height: 1080 },
            audio: {
                echoCancellation: true, // 启用回声消除
            },
        });
        mediaRecorder = new MediaRecorder(videoStream);
        return videoStream;
    }
}
document.getElementById("startButton").addEventListener("click", async () => {
    //这里要先判断权限，如果没有相机和麦克风的权限，需要先获取，如果有则开始录音
    //    document.getElementById('ImitateVedio').play()
    document.getElementById("startButton").style.display = "none";
    document.getElementById("PreviewBody").style.display = "none";
    document.getElementById("stopButton").style.display = "block";
    document.getElementById("videoPreview").style.display = "block";
    document.getElementById("videoPreview").style.transform = "scaleX(-1)";
    document.getElementById("playButton").style.display = "none";
    document.getElementById("playVedio").style.display = "none";
    videoStream = await getMediaStream();
    if (videoStream) {
        mediaRecorder.start();
        document.getElementById("videoPreview").srcObject = videoStream;
        document.getElementById("videoPreview").muted = true;
        document.getElementById("videoPreview").play();
        mediaRecorder.ondataavailable = (event) => {
            if (event.data.size > 0) {
                chunks.push(event.data);
            }
        };
        currentTimestamp = Date.now();
        operationName = "ing";
        additionalInfo = "video";
        CommonNetWork();
    }
    isRecording = false;
});
document.getElementById("stopButton").addEventListener("click", () => {
    if (videoStream) {
        const tracks = videoStream.getTracks();
        // 遍历并停止每个视频轨道，关闭摄像头视频流
        tracks.forEach((track) => {
            track.stop();
        });
        mediaRecorder.stop();
        mediaRecorder.onstop = () => {
            blob = new Blob(chunks, { type: "video/mp4" });
            // 上传视频数据
            uploadVideo(blob);
            chunks = [];
        };
        document.getElementById("videoPreview").srcObject = null;
        isRecording = true;
        document.getElementById("startButton").style.display = "none";
        document.getElementById("PreviewBody").style.display = "none";
        document.getElementById("stopButton").style.display = "none";
        document.getElementById("videoPreview").style.display = "none";
        document.getElementById("playButton").style.display = "block";
        document.getElementById("playVedio").style.display = "block";
    }
});
document.getElementById("playButton").addEventListener("click", () => {
    var video = document.getElementById("playVedio");
    // 创建 source 元素
    var source = document.createElement("source");
    // 设置 source 元素的属性
    source.type = "video/mp4";
    source.src =
        videoUrl +
        "/" +
        userid +
        "—" +
        scene +
        "—" +
        sceneLevel +
        "—" +
        courseType +
        "—" +
        classType +
        "—" +
        classSort +
        "—" +
        groupId +
        "—" +
        currentTimestamp +
        ".mp4";
    video.appendChild(source);
    video.preload = "metadata";
    // 播放视频
    video.load(); // 先加载视频
    video.play(); // 然后播放视频
});
function uploadVideo(blob) {
    const blobChunk = blob;
    var chunkSize = 1024 * 1024;
    let start = 0; // 从0开始切片
    let count = 1; //从1开始
    var totalPieces = Math.ceil(blobChunk.size / chunkSize); //总数

    while (start < blobChunk.size) {
        var end = start + chunkSize;
        if (end > blobChunk.size) {
            //小于1M也传
            end = blobChunk.size;
        }
        uploadChunk(blobChunk.slice(start, end), count, totalPieces, end == blobChunk.size);
        start += chunkSize;
        count++;
    }
}
function uploadChunk(chunk, count, totalPieces, bLast) {
    ImitatefileName =
        userid +
        "—" +
        scene +
        "—" +
        sceneLevel +
        "—" +
        courseType +
        "—" +
        classType +
        "—" +
        classSort +
        "—" +
        groupId +
        "—" +
        currentTimestamp +
        ".mp4";
    var formData = new FormData();
    formData.append("audioFile", chunk);
    formData.append("sliceNumber", count);
    formData.append("totalSlices", totalPieces);
    formData.append("fileName", ImitatefileName);
    formData.append("userid", userid);
    // 使用原生的fetch API示例（可替换为XMLHttpRequest等方式）
    fetch(CommonUrl + "/test/uploadSlice", {
        method: "post",
        headers: {
            Authorization: `Bearer ${token}`,
        },
        body: formData,
    })
        .then((res) => {
            // 上传成功后的处理
            if (bLast) {
                alert("上传成功");
                // alert(JSON.stringify(res));
            }
        })
        .catch((res) => {
            // 上传失败后的处理
            alert("上传失败");
            // alert(JSON.stringify(res));
        });
}

function reqPermission(one_per, callback) {
    var perms = new Array();
    if (one_per) {
        perms.push(one_per);
    } else {
        perms = ["library", "camera"];
    }
    api.requestPermission(
        {
            list: perms,
            code: 100001,
        },
        function (ret, err) {
            if (callback) {
                callback(ret);
                return;
            }
            var str = "请求结果：\n";
            str += "请求码: " + ret.code + "\n";
            str += '是否勾选"不再询问"按钮: ' + (ret.never ? "是" : "否") + "\n";
            str += "请求结果: \n";
            var list = ret.list;
            for (var i in list) {
                str += list[i].name + "=" + list[i].granted + "\n";
            }
            console.log(JSON.stringify(ret));
        }
    );
}
